#coding: utf-8

import re
from django import forms

from django.template.loader import render_to_string
from django.conf import settings
from django.utils.encoding import smart_unicode
from django.utils.hashcompat import sha_constructor

from django.contrib.auth import authenticate, login
from django.contrib.auth.models import User
from django.contrib.sites.models import Site

from models import GuestBook

alnum_re = re.compile(r'^\w+$')

class LoginForm(forms.Form):
    
    username = forms.CharField(label=u"用户名", max_length=30, widget=forms.TextInput())
    password = forms.CharField(label=u"密码", widget=forms.PasswordInput(render_value=False))
    remember = forms.BooleanField(label=u"记住我", help_text=u"如果勾选，登陆状态将会保持三周", required=False)    
    user = None
    
    def clean(self):
        if self._errors:
            return
        user = authenticate(username=self.cleaned_data["username"], password=self.cleaned_data["password"])
        if user:
            if user.is_active:
                self.user = user
            else:
                raise forms.ValidationError(u"帐号未激活")
        else:
            raise forms.ValidationError(u"用户名或密码不正确")
        return self.cleaned_data
    
    def login(self, request):
        if self.is_valid():
            login(request, self.user)
            request.user.message_set.create(message=u"登陆成功 %(username)s." % {'username': self.user.username})
            if self.cleaned_data['remember']:
                request.session.set_expiry(60 * 60 * 24 * 7 * 3)
            else:
                request.session.set_expiry(0)
            return True
        return False
    
    
class SignupForm(forms.Form):
    
    username = forms.CharField(label=u'用户名', max_length=30, widget=forms.TextInput(), help_text=u'建议用公司邮箱前面的用户名，只能包含字母，数字和下划线')
    name = forms.CharField(label=u'姓名', max_length=30, widget=forms.TextInput())
    password1 = forms.CharField(label=u'密码', widget=forms.PasswordInput(render_value=False))
    password2 = forms.CharField(label=u'密码确认', widget=forms.PasswordInput(render_value=False))
    email = forms.EmailField(label = u'工作邮箱', required = True, widget = forms.TextInput())
    
    def clean_username(self):
        if not alnum_re.search(self.cleaned_data["username"]):
            raise forms.ValidationError(u'用户名只能包含字母，数字和下划线。')
        try:
            user = User.objects.get(username__iexact=self.cleaned_data["username"])
        except User.DoesNotExist:
            return self.cleaned_data["username"]
        raise forms.ValidationError(u'用户名已经存在。')
    
    def clean(self):
        if "password1" in self.cleaned_data and "password2" in self.cleaned_data:
            if self.cleaned_data["password1"] != self.cleaned_data["password2"]:
                raise forms.ValidationError(u"两次输入的密码不一致")
        return self.cleaned_data
    
    def save(self):
        username = self.cleaned_data["username"]
        name = self.cleaned_data["name"]
        email = self.cleaned_data["email"]
        password = self.cleaned_data["password1"]        
        new_user = User.objects.create_user(username, email, password)
        new_user.message_set.create(message=u"注册成功！")
        new_user.is_active = True
        new_user.last_name = name
        new_user.save()
        return username, password # required for authenticate()
    
class GuestBookForm(forms.Form):
    msg = forms.CharField(label=u'留言',max_length=2000,widget=forms.Textarea(),required=True)
    
    def save(self, user):
        item = GuestBook(msg=self.cleaned_data['msg'], user=user)
        item.save()
        return self.cleaned_data['msg']